﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Threading;
using System.Windows.Forms;

namespace CUMTConnect
{
	class Login
	{
		/*
		 * judge that if has loged in
		 */
		public static bool IsLogIn()
		{
			Dictionary<String, String> dic = new Dictionary<string, string>();
			String html = HTTPRequest.Get("http://10.2.5.251", dic);
			// if has loged in, that page's title shouble 注销页
			if (html.Contains("注销页"))
			{
				return true;
			}
			else
			{
				return false;
			}
		}

		public static bool LogIn(ref NotifyIcon notify)
		{
			// delay seconds mapping, SelectedIndex -> DelaySeconds
			int[] delay = { 0, 1, 2, 3, 5, 10 };

			Logger.Log.Info("Wait for {0} second(s)", delay[Convert.ToInt32(ConfigurationManager.AppSettings["DelaySecondsIndex"])]);
			// Sleep some seconds so that windows could configurate the network setting
			Thread.Sleep(delay[Convert.ToInt32(ConfigurationManager.AppSettings["DelaySecondsIndex"])] * 1000);

			// Check whether the connected WiFi is the campus network entrance
			if (ConfigurationManager.AppSettings["WLANListenList"].Contains(WIFI.GetCurrentSSID()))
			{
				// user set to Check if is login
				if (Convert.ToBoolean(ConfigurationManager.AppSettings["CheckIsLogIn"]))
				{
					// if has loged in, then no action and return
					if (Login.IsLogIn())
					{
						return false;
					}
				}

				// Carrieroperator mapping, SelectedIndex -> Carrieroperator
				String[] Carrieroperator = { "", "cmcc", "unicom", "telecom" };
				// Construct args dictionary
				Dictionary<String, String> dic = new Dictionary<string, string>();
				dic["c"] = "Portal";
				dic["a"] = "login";
				dic["login_method"] = "1";
				StringBuilder stringBuilder = new StringBuilder();
				stringBuilder.Append(ConfigurationManager.AppSettings["StudentID"]);
				int selectedIndex = Convert.ToInt32(ConfigurationManager.AppSettings["Carrieroperator"]);
				if (selectedIndex != 0)
				{
					stringBuilder
						.Append("@")
						.Append(Carrieroperator[selectedIndex]);
				}
				dic["user_account"] = stringBuilder.ToString();
				dic["user_password"] = ConfigurationManager.AppSettings["Password"];
				
				// Send a login request
				String res = HTTPRequest.Get("http://10.2.5.251:801/eportal/", dic);
				
				// show a tips
				notify.ShowBalloonTip(2000);
				return true;
			}
			return false;
		}
	}
}
